<?php


namespace App\Models\Admin;


use App\Log\CustomerServiceAgentLog;

class CustomerServiceAgent extends Base
{
    const OPERATE_PID = 1;
    const MODEL = 'customer_service_agent';

    protected $table = 'customer_service_agent';
    protected $guarded = [];
    protected $dateFormat = 'U';
    protected $hidden = [
        'password',
    ];

    public function role()
    {
        return $this->belongsTo(CustomerServiceRole::class,'cust_role','id');
    }

    public static function getListAll($where)
    {
        $list=self::getwhere($where)
            ->select('id','name')
            ->get();
        return $list;
    }

    public static function getList($where=[],$skip=0,$size=10)
    {
        $list=self::getwhere($where)
            ->with([
                'role:id,name'
            ])
            ->skip($skip)->take($size)
            ->get()->transform(function ($i)
            {
                if(!$i->user_ids) $i->user_num=0;
                else $i->user_num=count(explode(',',$i->user_ids));
                return $i;
            });
        return $list;
    }

    public static function getCount($where)
    {
        $count=self::getWhere($where)->count();
        return $count;
    }

    public static function getWhere($where)
    {
        $select=self::where([]);
        if(!empty($where['keyword']))
        {
            $keyword='%'.$where['keyword'].'%';
            $select=$select->where(function ($query) use ($keyword)
            {
                $query->where('name','like',$keyword)->orWhere('mobile','like',$keyword)->orWhere('nickname','like',$keyword)->orWhere('account','like',$keyword);
            });
        }
        if(!empty($where['cust_role']))
        {
            $select=$select->where('cust_role',$where['cust_role']);
        }
        if(!empty($where['service_status']))
        {
            $select=$select->where('service_status',$where['service_status']);
        }
        if(!empty($where['cust_role']))
        {
            $select=$select->where('cust_role',$where['cust_role']);
        }
        return $select;
    }

    public static function getInfo($id)
    {
        $info=self::where('id',$id)
            ->with([
                'role:id,name'
            ])->first();
        return $info;
    }

    public static function addLog($pre,$next,$type,$method='')
    {
        $info = AdminOperateModule::where('pid',self::OPERATE_PID)->where('type',$type)->where('model',self::MODEL)->when($method,function ($query)use ($method){
            $query->where('method',$method);
        })->first();
        if (!empty($info)){
            $goodsCategoryLog = new CustomerServiceAgentLog($pre,$next,$info);
            $goodsCategoryLog->addLog();
        }
    }
}
